package com.liveinstars.im.handler;

import com.liveinstars.im.core.SessionManager;
import com.liveinstars.im.corebean.ServerLoginMessage;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 1、保持服务器间的心态 2、转发消息
 * 
 * @author ting
 *
 */
@Sharable
@Service
public class ServerLoginHandler extends SimpleChannelInboundHandler<ServerLoginMessage> {

	private static final Logger LOGGER = LoggerFactory.getLogger(ServerLoginHandler.class);

	@Autowired
	private SessionManager sessionManager;

	@Override
	protected void channelRead0(ChannelHandlerContext channelHandlerContext,
			ServerLoginMessage message) throws Exception {

		LOGGER.info("服务器登录。");
		// 处理服务器到服务器的登录
		if (!sessionManager.serverLogin(channelHandlerContext, message)) {
			LOGGER.info("服务器登录失败，关闭。");
			channelHandlerContext.channel().close();
			return;
		}

		ReferenceCountUtil.release(message);
	}
}